﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsCommandStudy
{
    public partial class FormBase : Form
    {
        private Dictionary<string, Action<object, EventArgs>> actions = new Dictionary<string, Action<object, EventArgs>>();

        public FormBase()
        {
            InitializeComponent();
        }

        private void FormBase_Load(object sender, EventArgs e)
        {
            foreach (var button in this.GetButtons())
            {
                var item = this.mainToolStrip.Items.Add(button);
                item.Name = button;
                item.Click += this.Item_Click;
            }
        }

        protected FormBase RegisterAction(string name, Action<object, EventArgs> action)
        {
            this.actions[name] = action;

            return this;
        }

        private IEnumerable<string> GetButtons()
        {
            return new List<string> { "添加" }.Concat(this.GetExtraButtons());
        }

        protected virtual IEnumerable<string> GetExtraButtons()
        {
            return Enumerable.Empty<string>();
        }

        private void Item_Click(object sender, EventArgs e)
        {
            var name = (sender as ToolStripItem).Name;

            this.FindAction(name)(sender, e);
        }

        private Action<object, EventArgs> FindAction(string name)
        {
            if (this.actions.ContainsKey(name))
            {
                return actions[name];
            }

            var method = this.GetType().GetMethod(name + "_Item_Click", BindingFlags.Instance | BindingFlags.NonPublic);

            return (Action<object, EventArgs>)method.CreateDelegate(typeof(Action<object, EventArgs>), this);
        }

        protected virtual void 添加_Item_Click(object sender, EventArgs e)
        {
        }
    }
}
